<template>
  <view>
    <u-navbar :is-back="true" title="设置" :border-bottom="false"> </u-navbar>
    <view>
      <u-cell-group>
        <u-cell-item title="头像" :arrow="true" hover-class="none" @click="updateAvatar">
          <u-avatar :src="avatarUrl" size="100"></u-avatar>
        </u-cell-item>
      </u-cell-group>
      <u-cell-group>
        <u-cell-item title="昵称" :arrow="true" hover-class="none" @click="updateName">
          {{ vuex_user.nickName || '昵称' }}
        </u-cell-item>
      </u-cell-group>
      <u-cell-group>
        <u-cell-item title="ID" :arrow="false" hover-class="none">
          {{ useId }}
        </u-cell-item>
      </u-cell-group>
    </view>
    <u-modal v-model="showModel" @confirm="confirmName" ref="uModal" :async-close="true" title="设置昵称">
      <view class="slot-content">
        <u-input v-model="nickName" type="text" :border="false" placeholder="请输入昵称" />
      </view>
    </u-modal>

    <view class="btn">
      <u-button type="default" @click="logout" plain>退出登录</u-button>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { baseURL } from 'api/constant.js'
import { userUpdate } from 'api/findData.js'
export default {
  data() {
    return {
      nickName: null,
      showModel: false
    }
  },
  onLoad() {},
  created() {
    this.nickName = this.vuex_user.nickName
  },
  computed: {
    ...mapState(['vuex_account', 'vuex_version', 'vuex_account', 'vuex_token', 'vuex_user']),
    useId() {
      const lastNineChars = this.vuex_account.slice(-9)
      return lastNineChars
    },
    avatarUrl() {
      return baseURL + '/' + this.vuex_user.avatarUrl
    }
  },
  methods: {
    updateName() {
      this.showModel = true
    },
    /**
     * @desc: 修改nickName
     * @author: majun
     */
    async confirmName() {
      if (!this.nickName) {
        this.showModel = false
        return this.$mytip.toast('请输入昵称')
      }
      try {
        await userUpdate(this.vuex_account, { nick: this.nickName })
        this.vuex_user.nickName = this.nickName
        this.$u.vuex('vuex_user', this.vuex_user)
        this.$mytip.toast('昵称修改成功！')
        this.showModel = false
      } catch (error) {
        this.$mytip.toast('昵称修改失败！')
        this.showModel = false
      }
    },
    /**
     * @desc: 跳头像修改
     * @author: majun
     */
    updateAvatar() {
      this.$u.route('/pages/profile/avatar')
    },
    logout() {
      // 登录成功修改token与用户信息
      this.$u.vuex('vuex_token', '')
      this.$u.vuex('vuex_user', {})
      this.$u.vuex('vuex_vip', {})
      return uni.reLaunch({
        url: '/pages/week/index'
      })
    }
  }
}
</script>

<style lang="scss">
.btn {
  margin: 20rpx;
}

.slot-content {
  padding: 40rpx;
}

.version {
  position: absolute;
  bottom: 20rpx;
  width: 100%;
  text-align: center;
}
</style>
